package com.ycz.shiroboot.config;

import com.ycz.shiroboot.domain.User;
import com.ycz.shiroboot.service.UserService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;

/**
 * @Description 自定义Realm，继承AuthorizingRealm类，重写认证和授权方法
 * @ClassName UserRealm
 * @Author yanchengzhi
 * @date 2021.09.25 15:36
 */
public class UserRealm extends AuthorizingRealm {

    @Autowired
    private UserService userService;

    // 授权
    // 授权
//    @Override
//    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
//        System.out.println("进入授权方法！");
//        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
//        // 获取当前登录用户
//        Subject subject = SecurityUtils.getSubject();
//        User currentUser = (User)subject.getPrincipal();
//        info.addStringPermission(currentUser.getPers());
//        return info;
//    }

    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        System.out.println("进入授权方法！");
        return null;
    }

    // 认证
    // 认证
    // 认证
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        System.out.println("进入认证方法！");
        // 将token进行转换，token是前端页面传过来的用户名+密码的加密封装
        UsernamePasswordToken usernamePasswordToken = (UsernamePasswordToken) token;
        User user = userService.findByUsername(usernamePasswordToken.getUsername());
        if(user == null) { // 用户名校验
            return null;
        }
        // 密码校验，Shiro自动完成
//        return new SimpleAuthenticationInfo(user, user.getPassword(),"");
        return new SimpleAuthenticationInfo("",user.getPassword(),"");
    }


//    @Override
//    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
//        System.out.println("进入认证方法！");
//        // 用户名和密码，应该从数据库中取，这里用静态数据代替
//        String name = "ycz";
//        String password = "ycz123456";
//        // 将token进行转换，token是前端页面传过来的用户名+密码的加密封装
//        UsernamePasswordToken usernamePasswordToken = (UsernamePasswordToken) token;
//        // 用户名校验
//        if (!usernamePasswordToken.getUsername().equals(name)) {
//            return null;  // 返回null的话，会自动抛出UnknownAccountException异常
//        }
//        // 密码校验，Shiro自动完成
//        return new SimpleAuthenticationInfo("", password, "");
//    }
}

//    @Override
//    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
//        System.out.println("进入认证方法！");
//        return null;
//    }
//}
